from sympy import *
from sympy.core.symbol import _symbol
from .hyperbola import Hyperbola

# x,y = [Dummy("quadratic_utils_dummy",real=True) for i in range(2)]

x = _symbol("x", real=True)
y = _symbol("y", real=True)


def line_and_quadratic(line, quadra, x=x, y=y, first=True) -> Expr:
    if isinstance(line, Line):
        l_eq = line.equation(x, y)
    elif isinstance(line, Expr):
        l_eq = line
    if isinstance(quadra, (Hyperbola, Ellipse, Circle, Parabola)):
        e_eq = quadra.equation(x, y)
    elif isinstance(quadra, Expr):
        e_eq = quadra

    if not first:
        x, y = y, x

    eq = e_eq.subs(y, list(solveset(l_eq, y))[0])

    def _to_human_expr(expr: Expr, x: Symbol) -> Expr:
        expr=expand(expr)
        a = factor(expr.coeff(x, 2))
        b = factor(expr.coeff(x, 1))
        c = factor(expr.coeff(x, 0))

        return Add(
            *list(filter(lambda item: item != 0, [a * x**2, b * x, c])), evaluate=False
        )
    
    expr_check = factor(expand(eq))
    if type(expr_check) == Mul:
        answer = 1
        for expr in expr_check.args:
            if expr.has(x):
                answer = answer * expr
        return _to_human_expr(answer, x)
    if type(expr_check) == Add:
        return _to_human_expr(expr_check, x)
    else:
        raise ("something wrong!")
